import request from '@/config/axios'

// 能耗报告数据 API 路径
export const reportApi = {
  page: '/energy/report/page',
  create: '/energy/report/create',
  update: '/energy/report/update',
  delete: '/energy/report/delete',
  get: '/energy/report/get',
  batchImport: '/energy/report/batch-import',
  importFile: '/energy/report/import-file',
  testUpload: '/energy/report/test-upload',
  export: '/energy/report/export'
}

// 能耗报告数据类型
export interface ReportDataVO {
  id: number
  deviceId: string
  reportDataType: string
  reportDataValue: number
  reportDataLevel: string
  reportDataTime: string
  energyConsumption: number
  message: string
  status: string
  createTime: string
  uploadType?: number // 上传标识：1-批量上传，2-随机生成上传
}

// 能耗报告数据分页请求参数
export interface ReportDataPageReqVO extends PageParam {
  deviceId?: string
  reportDataType?: string
  reportDataLevel?: string
  status?: string
  reportDataTime?: string[]
  createTime?: string[]
  uploadType?: number // 上传标识查询参数
  uploadTypeExists?: boolean // 标记是否只查询有uploadType值的数据
}

// 获取能耗报告数据分页列表
export const getReportDataPage = async (params: ReportDataPageReqVO) => {
  return await request.get<PageResult<ReportDataVO[]>>({ url: reportApi.page, params })
}

// 获取能耗报告数据详情
export const getReportData = async (id: number) => {
  return await request.get<ReportDataVO>({ url: reportApi.get, params: { id } })
}

// 新增能耗报告数据
export const createReportData = async (data: Omit<ReportDataVO, 'id' | 'createTime'>) => {
  // 设置默认上传类型为随机生成上传
  if (data.uploadType === undefined) {
    data.uploadType = 2 // 随机生成上传
  }
  return await request.post<number>({ url: reportApi.create, data })
}

// 修改能耗报告数据
export const updateReportData = async (data: Omit<ReportDataVO, 'createTime'>) => {
  return await request.put<boolean>({ url: reportApi.update, data })
}

// 删除能耗报告数据
export const deleteReportData = async (id: number) => {
  return await request.delete<boolean>({ url: reportApi.delete, params: { id } })
}

// 批量导入能耗报告数据
export const batchImportReportData = async (
  dataList: Omit<ReportDataVO, 'id' | 'createTime'>[]
) => {
  // 设置默认上传类型为批量上传
  dataList.forEach((item) => {
    if (item.uploadType === undefined) {
      item.uploadType = 1 // 批量上传
    }
  })
  return await request.post<number>({ url: reportApi.batchImport, data: dataList })
}

// 通过文件导入能耗报告数据
export const importReportDataFile = async (file: File) => {
  console.log('准备上传文件：', file.name, file.size, file.type)

  const formData = new FormData()
  formData.append('file', file)

  // 直接记录文件信息而不使用entries
  console.log('FormData添加文件:', file.name, file.type, file.size)
  console.log('请求URL:', `/energy/report/import-file`)

  try {
    // 添加可选的超时参数，避免网络延迟导致的问题
    const response = await request.post<number>({
      url: reportApi.importFile,
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      timeout: 60000 // 增加超时时间到60秒
    })
    console.log('上传响应:', response)
    return response
  } catch (error: any) {
    console.error('上传请求失败:', error)
    if (error.response) {
      console.error('错误状态码:', error.response.status)
      console.error('错误数据:', error.response.data)
    }
    throw error
  }
}

// 测试文件上传
export const testUpload = async (file: File) => {
  console.log('测试上传文件：', file.name, file.size, file.type)

  const formData = new FormData()
  formData.append('file', file)

  console.log('FormData添加文件:', file.name, file.type, file.size)
  console.log('请求URL:', reportApi.testUpload)

  try {
    const response = await request.post<any>({
      url: reportApi.testUpload,
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      timeout: 60000
    })
    console.log('测试上传响应:', response)
    return response
  } catch (error: any) {
    console.error('测试上传失败:', error)
    if (error.response) {
      console.error('错误状态码:', error.response.status)
      console.error('错误数据:', error.response.data)
    }
    throw error
  }
}

// 上报数据类型选项
export const reportDataTypeOptions = [
  { label: '电压', value: 'voltage' },
  { label: '电流', value: 'currents' },
  { label: '功率', value: 'activePower' },
  { label: '温度', value: 'temperature' }
]

// 上报数据级别选项
export const reportDataLevelOptions = [
  { label: '正常', value: 'info', type: 'success' },
  { label: '警告', value: 'warning', type: 'warning' },
  { label: '危险', value: 'danger', type: 'danger' }
]

// 处理状态选项
export const reportStatusOptions = [
  { label: '未处理', value: 'unprocessed', type: 'info' },
  { label: '处理中', value: 'processing', type: 'warning' },
  { label: '已处理', value: 'processed', type: 'success' },
  { label: '已忽略', value: 'ignored', type: 'default' }
]

// 上传类型选项
export const uploadTypeOptions = [
  { label: '批量上传', value: 1 },
  { label: '随机生成上传', value: 2 }
]

// 导出能耗报告数据
export const exportReportData = async (params: ReportDataPageReqVO) => {
  try {
    const filename = '能耗报告数据_' + new Date().getTime() + '.xlsx'
    console.log('开始下载请求:', reportApi.export, params)
    const res = await request.download({
      url: reportApi.export,
      params
    })
    console.log('下载请求完成，数据大小:', res ? res.size : '未知')

    if (!res || res.size === 0) {
      console.error('下载内容为空')
      throw new Error('下载内容为空')
    }

    // 检查响应类型
    console.log('响应类型:', res.type)

    // 创建Blob对象，并执行下载
    const blob = new Blob([res], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', filename)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link) // 移除a标签
    window.URL.revokeObjectURL(url) // 释放url
    return res
  } catch (error) {
    console.error('导出处理过程中出错:', error)
    throw error
  }
}
